﻿using App.Core.Data;
using App.Core.Entities;
using App.Core.Services;
using AppTemplate.Infrastructure.Paging;
using AppTemplate.Infrastructure.ServiceBase;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace App.Core.ServiceImpls
{
    public class UserService : ServiceBase<User>, IUserService
    {
        private readonly AppDbContext dbContext;

        public UserService(AppDbContext dbContext) : base(dbContext)
        {
            this.dbContext = dbContext;
        }

        public Task<User?> Auth(string account, string password)
        {
            return Task.Run(async () =>
            {
                return await dbContext.Users.FirstOrDefaultAsync(u => u.Account == account && u.Password == password);
            });
        }

        public Task<User?> GetUserByAccount(string account)
        {
            return dbContext.Users.FirstOrDefaultAsync(u => u.Account == account);
        }

        public Task<PageSearchResult<User>> PageSearch(int pageIndex, int pageSize, string? account = default, string? name = default)
        {
            Expression<Func<User, bool>> predicate = PredicateBuilder.New<User>(true);
            if (!string.IsNullOrEmpty(account))
            {
                predicate = predicate.And(u => u.Account == account);
            }
            if (!string.IsNullOrEmpty(name))
            {
                predicate = predicate.And(u => u.Name == name);
            }

            var pageResult = base.PageSearch(pageIndex, pageSize, predicate);
            return pageResult;
        }
    }
}
